<script setup>
import { ref, computed } from 'vue'
// 导入相关接口
import {
    Delete,
    Edit,
    Refresh
} from '@element-plus/icons-vue'
import {
    getSeatsPageApi,
    addSeatsApi,
    querySeatsByIdApi,
    editSeatsApi,
    deleteSeatsApi,
    seatsStatusByStatusApi
} from '@/api/backend/seats.js'

import { ElMessage, ElMessageBox } from 'element-plus'

const dialogFormVisible = ref(false)
const title = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const disabled = ref(false)
const total = ref(0)
const tableData = ref([])
const handleSizeChange = (val) => {
    getSeatsPage();
}
const handleCurrentChange = (val) => {
    getSeatsPage();
}
const typeMapping = {
    1: '启用',
    0: '停用'
}
const typeMapping2 = {
    1: '有人',
    0: '没人'
}
const transformedTableData = computed(() => {
    return tableData.value.map(item => {
        return {
            ...item,
            cwstatus: typeMapping[item.cwstatus],
            systatus: typeMapping2[item.systatus]
        }
    })
})
const XSDialogFormVisible = (xst, id) => {
    if (xst == '编辑餐位') {
        querySeatsById(id);
        // console.log(id);
    }
    dialogFormVisible.value = true;
    title.value = xst;
}
function dialogFormCancelClick() {
    qc();
    dialogFormVisible.value = false;
}
function dialogFormConfirmClick() {
    // 校验
    submitForm(seatsRef)
        .then((result) => {
            if (result) {
                if (title.value == '添加餐位') {
                    addSeats();
                } else if (title.value == '编辑餐位') {
                    editSeats();
                } else {
                    ElMessage.success('数据异常')
                }
                qc();
                dialogFormVisible.value = false;
            } else {
                // 处理结果为 false 的情况
                ElMessage.error('校验不通过')
            }

        });
}
const ids = ref([]);
const handleSelectionChange = (val) => {
    let it = [];
    val.forEach((item) => {
        it.push(item.id);
    });
    ids.value = it;
}
const getSeatsPage = async () => {
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
    }
    let result = await getSeatsPageApi(params);
    if (result.code === 1) {
        tableData.value = result.data.records || []
        total.value = result.data.total
        return;
    } else {
        return;
    }
}
getSeatsPage();
const seatsData = ref({
    cwstatus: 1,
    id: null,
    name: '',
    number: 0,
    systatus: 0
})
const qc = (() => {
    seatsData.value.id = null;
    seatsData.value.name = '';
    seatsData.value.number = 0;
    seatsData.value.systatus = 0;
    seatsData.value.cwstatus = 1;
})
const seatsRef = ref(null);
const seatsRules = {
    name: [
        { required: true, message: '请输入餐位名', trigger: 'blur' },
    ],
}
const submitForm = (fromEL) => {
    return new Promise((resolve, reject) => {
        fromEL.value.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        })
    });
}
const addSeats = async () => {
    let result = await addSeatsApi(seatsData.value);
    if (result.code === 1) {
        ElMessage.success(result.data ? result.data : '添加成功')
        getSeatsPage();
        return;
    } else {
        return;
    }
}
const querySeatsById = async (id) => {
    let result = await querySeatsByIdApi(id);
    if (result.code === 1) {
        seatsData.value.id = result.data.id;
        seatsData.value.name = result.data.name;
        seatsData.value.number = result.data.number;
        seatsData.value.systatus = result.data.systatus;
        seatsData.value.cwstatus = result.data.cwstatus;
        return;
    } else {
        return;
    }
}
const editSeats = async () => {
    let result = await editSeatsApi(seatsData.value);
    if (result.code === 1) {
        ElMessage.success(result.data);
        getSeatsPage();
        return;
    } else {
        return;
    }
}
const deleteSeats = async (i) => {
    if (i == null) {
        i = ids.value.join(',');
    }
    let result = await deleteSeatsApi(i);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getSeatsPage();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '删除失败')
        return;
    }
}
const seatsStatusByStatus = async (s, i) => {
    const params = {
        id: '',
        status: s
    }
    if (i == null) {
        params.id = ids.value.join(',');
    } else {
        params.id = i;
    }
    let result = await seatsStatusByStatusApi(params);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getSeatsPage();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '修改失败')
        return;
    }
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>餐位管理</span>
                <!-- button -->
                <el-button type="warning" plain @click="seatsStatusByStatus(1)">
                    批量启用
                </el-button>
                <el-button type="warning" plain @click="seatsStatusByStatus(0)">
                    批量停用
                </el-button>
                <el-button type="danger" plain @click="deleteSeats()">
                    批量删除
                </el-button>
                <el-button type="success" plain @click="XSDialogFormVisible('添加餐位')">
                    添加餐位
                </el-button>
                <!-- 使用dialog组件 , 表单内容,餐位名称,座位数量  -->
                <el-dialog v-model="dialogFormVisible" align-center width="33%" :show-close="false"
                    :close-on-click-modal="false" :close-on-press-escape="false">
                    <template #header="{ titleId, titleClass }">
                        <div class="my-header">
                            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
                        </div>
                    </template>
                    <el-form :model="seatsData" label-position="left " label-width="100px" ref="seatsRef"
                        :rules="seatsRules">
                        <el-form-item label="餐位名称:" prop="name">
                            <el-input v-model="seatsData.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="座位数量:">
                            <el-input-number v-model="seatsData.number" :min="0" :max="100" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormCancelClick()">取消</el-button>
                            <el-button @click="dialogFormConfirmClick()">确认</el-button>
                        </span>
                    </template>
                </el-dialog>

            </div>
        </template>
        <el-table :data="transformedTableData" stripe style="width: 100%" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
            <el-table-column label="选择" width="30px" type="selection"> </el-table-column>
            <el-table-column label="餐位名称" prop="name"></el-table-column>
            <el-table-column label="座位数量" prop="number"></el-table-column>
            <el-table-column label="餐位状态" prop="cwstatus">
                <template #default="{ row }">
                    <el-text type="primary">{{ row.cwstatus }}</el-text>
                    <el-button :icon="Refresh" size="small" circle @click="seatsStatusByStatus((row.cwstatus == '停用' ? 1 : 0), row.id)" />
                </template>
            </el-table-column>
            <el-table-column label="使用状态" prop="systatus">
                <template #default="{ row }">
                    <el-text type="primary">{{ row.systatus }}</el-text>
                </template>
            </el-table-column>
            <el-table-column label="最后操作时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="XSDialogFormVisible('编辑餐位', row.id)" />
                    <el-button type="danger" :icon="Delete" circle @click="deleteSeats(row.id)" />
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <div>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :disabled="disabled"
                :page-sizes="[5, 15, 30]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.el-pagination {
    margin-top: 10px;
    justify-content: center;
}

//

.el-dialog .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>